package main.model;

import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

import main.util.HibernateContext;
import javax.persistence.GenerationType;

@Entity
@Table(name="airport")
public class Airport implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7588158338978370281L;
	private long id;
	private String name;
	private List<AirportCompany> companies = new ArrayList<AirportCompany>();
	private List<Airline> airlines = new ArrayList<Airline>();
	
	public Airport() {}
	
	public Airport(String name) {
		this.name = name;
	}
	
	@Id
	@GeneratedValue
	@Column(name="id")
	public long getId() { return id; }
	public void setId(long id) { this.id = id; }
	
	@Column(name="name")
	public String getName() { return name; }
	public void setName(String name) { this.name = name; }
	
	@OneToMany (mappedBy="airport", targetEntity= Airline.class,
            cascade=CascadeType.ALL,              fetch=FetchType.LAZY)
	public List<Airline> getAirlines() 
	{ 
		return airlines; 
	}
	public void setAirlines( List<Airline> airlines)                      
 	{ 
	 	this.airlines = airlines; 
	}
	
	@ManyToMany
	@JoinTable(name="airport_company",
			   joinColumns={@JoinColumn(name="airport_id")},
			   inverseJoinColumns={@JoinColumn(name="company_id")})
	public List<AirportCompany> getCompany()
	{
		return companies;
	}
	
	public void setCompany(List<AirportCompany> companies)
	{
		this.companies = companies;
	}
	
	public static Airport find(String name)
	{
		Session session = HibernateContext.getSession();
		Query query = session.createQuery("from Airport where name = :airName");
		query.setString("airName", name);
		Airport item = (Airport) query.uniqueResult();
		session.close();
		return item;
	}
	
//	/**
//	 * load the airport data
//	 */
//	public static void load() {
//		Session session = HibernateContext.getSession();
//		Transaction tx = session.beginTransaction();
//		
//		session.save(new Airport("Jerry1"));
//		session.save(new Airport("Jerry2"));
//		session.save(new Airport("Jerry3"));
//		session.save(new Airport("Jerry4"));
//		
//		tx.commit();
//		session.close();
//		
//		System.out.println("Airport Data Loaded");
//	}
}
